<template>

    <!-- 查询请假历史 -->
    
    <el-table
      :data="tableData"
      style="width: 100% ;"
      :default-sort="{ prop: 'time', order: 'descending' }"
    >
  
      <el-table-column prop="student_id" label="学号" width="180"></el-table-column>
      <el-table-column prop="name" label="姓名" width="100"></el-table-column>

      <el-table-column prop="start_date" label="开始时间" width="150"> </el-table-column>
      <el-table-column prop="end_date" label="结束时间" width="150"></el-table-column>
      <el-table-column prop="leave_type" label="请假类型" width="100"></el-table-column>
      <el-table-column prop="reason" label="请假原因" width="180"></el-table-column>
      <el-table-column prop="status" label="当前状态" width="120"></el-table-column>
      <el-table-column prop="created_at" label="申请时间" width="180"></el-table-column>
      <el-table-column label="" >

        <template v-slot="scope">
            <el-button type="success" @click="handleSuccess(scope)">同意</el-button>
            <el-button type="danger" @click="handleRejeced(scope)">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-6 flex justify-center">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="10"
        :total="max"
        @current-change="page($event)"
      >
      </el-pagination>
    </div>
</template>
  <script setup>
  import { ref, computed , onMounted} from "vue";
  import api from "@/modules/api";
  import studentLeaveHistory from "@/modules/leave/read-student-leave"
  import updateLeaveStatus from "@/modules/leave/update-leave-status";

  import deleteUser from "@/modules/common/delete-user";
  import { useRouter } from "vue-router";
  import { Delete, Search } from "@element-plus/icons-vue";
  import { ElLoading, ElMessage } from "element-plus";
  
  let isAdmin = localStorage.id == "admin";
  let isTeacher = localStorage.id;
  let router = useRouter();
  let data = ref([]);
  let offset = ref(1); // 默认从第一页开始
  let pageSize = ref(10); // 一页最多能显示 20 条数据
  let max = ref(0);
  let index = ref(0);
  
  // 计算属性，根据当前页码和每页显示数量来分页显示数据
  let tableData = computed(() => {
    return data.value.slice(index.value * 10, (index.value + 1) * 10);
  });
  
  
  /**
   * 翻页请求
   * @param {*} page 页码 
   */
  function page(page) {
    // 翻页请求
    console.log(page);
    offset.value = page;
    init(page)
  }
  
  // api(`select * from student`).then(res => {
  //   data.value = res.res;
  //   max.value = res.res.length;
  // });
  
  /**
   * 初始化加载
   * @param {*} page 页码
   */
  const  init = async (page = 1) =>{
    try {
  
      let res =  await studentLeaveHistory({ 
        page :!page ? offset.value : page, 
        size : pageSize.value , 
        grade : localStorage.getItem("grade"),
        major_id : localStorage.getItem("major_id"),
        class_name : localStorage.getItem("class_name")
    });
      if(res.success){
        let datas = [];
        
        res.students = res.students.filter(student => {
            if (student.leaves && student.leaves.length > 0) {
                // 将 leaves 数据整合到 students 对象中
                
                student.leaves.forEach(leave => {
                    // 可以在这里对 leave 数据进行处理，或者直接添加到 student 对象中
                    let params = {};
                    params.name = student.student_name;
                    params.leave_id = leave.leave_id;
                    params.start_date = leave.start_date;
                    params.end_date = leave.end_date;
                    params.leave_type = leave.leave_type;
                    params.reason = leave.reason;
                    params.status = leave.status === 'Pending' ? '申请中' : leave.status === 'Approved' ? '已同意' : leave.status === 'Rejected' ? '已拒绝' : '已完成';
                    params.created_at = leave.created_at;
                    params.student_id = leave.student_id;

                    datas.push(params);
                });
                console.log('datassss=====',datas);

                return true; // 返回 true 保留该学生对象
            } else {
                return false; // 返回 false 删除该学生对象
            }
        });

        console.log('datas=====',datas);
        data.value = datas,
        max.value = res.totalStudents

      }else{
        ElMessage({
          message: "查询失败",
          type: "error",
        })
  
      }
  
    } catch (error) {
      console.log(error);
    }
  }
  
  onMounted (() =>{
  
    init()
  })
  
  
  const handleSuccess = async (scope) =>{
    

    let params = {
        status : 'Approved',
        leave_id : scope.row.leave_id,
    }

    const res = await updateLeaveStatus(params);

    console.log(res);

    if(res.success){
        ElMessage({
            message : '已同意',
            type : 'success'
        });
        init();
    }
  }


  const handleRejeced = async (scope) =>{
    

    let params = {
        status : 'Rejected',
        leave_id : scope.row.leave_id,
    }

    const res = await updateLeaveStatus(params);


    if(res.success){
        ElMessage({
            message : '已拒绝',
            type : 'success'
        })
        init()
    }
  }


   

  
  /**
   * 删除学生信息
   * @param {*} id 学生id
   * @param {*} index 
   */
  function remove(id, index) {
    deleteUser({ col: "student", id: id }).then(res => {
      if (res.res) {
        api(`DELETE FROM achievement WHERE stucode='${id}';`).then(res => {
          router.go(0);
        });
      }
    });
  }
  let stuClass = ref("");
  


  </script>
  <style scoped lang="scss">
    .stu-name {
      width: 200px;
      margin-left: 20px;
    }
    .search-btn {
      margin-left: 10px;
    }
  
    .el-table .cell {
      text-align: center;
    }
  </style>
  